package com.company.ThreadLearn;

import com.sun.javafx.stage.StageHelper;

import java.util.LinkedList;
import java.util.Queue;

public class wait_notify {
    public wait_notify() throws InterruptedException {
        TaskQueue taskQueue = new TaskQueue();
        WorkerThread worker = new WorkerThread(taskQueue);
//        add task;
        taskQueue.addTask("Bob");
        Thread.sleep(1000);
        taskQueue.addTask("Alice");
        Thread.sleep(1000);
        taskQueue.addTask("Tim");
        Thread.sleep(1000);
//        worker.interrupt();
        worker.start();
        worker.interrupt();
        worker.join();
        System.out.println("END");
    }
}

class TaskQueue {

    final Queue<String> queue = new LinkedList<>();

    public synchronized String getTask() throws InterruptedException{
        while (this.queue.isEmpty()){
            this.wait();
        }
        return queue.remove();
    }
    public synchronized void addTask (String name){
        this.queue.add(name);
        this.notifyAll();
    }
}

class WorkerThread extends Thread{

    TaskQueue taskQueue;

    public WorkerThread(TaskQueue taskQueue){
        this.taskQueue = taskQueue;
    }

    @Override
    public void run() {
        String name = "";
        try {
            name = taskQueue.getTask();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        String result = "Hello, " + name + "!";
        System.out.println(result);
    }
}